import { getIp, getPositionByIp, getUserInfo, login, register } from '@/apis';
import { LoginParams, PositionData, RegisterParams } from '@/apis/types';
import config from '@/config';
import { getLocalStorageItem, setLocalStorageItem } from '@/utils/storage/localStorage';
import { defineStore } from 'pinia';
import { shallowReactive, toRef, toRefs } from 'vue';
import { UserResponseData, userActions, userGetters, userState, User } from './types';

const state = (): userState => {
    return {
        id: '64a30cf3cb9b942a24239c19',
        username: 'admin',
        role: 'user',
        avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
        cover:'',
        token: getLocalStorageItem(config.userTokenLocal) || '',
        pos: null
    }
}

const actions: userActions = {
    async _login(form: LoginParams) {
        const res = await login(form) as User;
        this.token = res.token;
        this.id = res._id;
        this.username = res.username;
        this.role = res.role;
        this.avatar = res.avatar;
        setLocalStorageItem(config.userTokenLocal, res.token);
    },
    async _register(form: RegisterParams) {
        const res = await register(form) as User;
        this.token = res.token;
        this.id = res._id;
        this.username = res.username;
        this.role = res.role;
        this.avatar = res.avatar;
        this.cover = res.cover;
        setLocalStorageItem(config.userTokenLocal, res.token);
    },
    async _getPosition() {
        const ip = (await getIp()).data;
        const localIp = getLocalStorageItem<string>(config.userIpLocal);
        if (ip === localIp) {
            this.pos = getLocalStorageItem<PositionData>(config.userPosLocal);
        } else {
            const pos = await getPositionByIp<PositionData>(ip);
            this.pos = pos;
            setLocalStorageItem(config.userPosLocal, pos);
        }
        setLocalStorageItem(config.userIpLocal, ip);
    },
    async _initUserInfo() {
        const token = getLocalStorageItem(config.userTokenLocal) as string;
        if (token) {
            getUserInfo(token).then((res) => {
                this.token = res.token;
                this.id = res._id;
                this.username = res.username;
                this.role = res.role;
                this.avatar = res.avatar;
                this.cover = res.cover;
            })
        } else {
            this.id = '64a30cf3cb9b942a24239c19';
            this.username = 'admin';
            this.role = 'user';
            this.avatar = 'https://img.yzcdn.cn/vant/cat.jpeg';
            this.cover = 'https://img.yzcdn.cn/vant/cat.jpeg';
            this.token = getLocalStorageItem(config.userTokenLocal) || '';
            this.pos = null;
        }
    }
}


const getters: userGetters = {

}



export const useUserStore = defineStore('user', {
    state,
    actions,
    getters,
});